import axios from 'axios'
import store from '@/store'
import {getToken} from '@/utils/auth'
import {Toast} from "vant";
import { CLIENT } from './constants';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 7000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
      Toast.loading("请求中...");
      if (store.getters.token) {
        config.headers['Authorization'] = getToken()
        config.headers['Client'] = CLIENT
      }
      return config
    },
    error => {
      console.log(error) // for debug
      return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
      Toast.clear();
      const res = response.data;
      if (res.code !== 200){
        return Promise.reject(res.message || "Error")
      }else{
        return res;
      }

    },
    error => {
      console.log('err' + error) // for debug
      Toast({
        message: error.message,
        type: 'fail',
        duration: 7 * 1000
      })
      return Promise.reject(error)
    }
)

export default service
